package dict

import (
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/copier"
	"strconv"
	"xpms/app/models"
	"xpms/cores"
	"xpms/cores/utils"
)

type Dict struct {
	Id           int64 `orm:"pk;column(id);" json:"Id,string"`
	DictId       string
	DictTypeCode string
	DictName     string
	Sort         int
	Status       int
	ProjectId    int64 `json:"ProjectId,string"`
}

func init() {
	orm.RegisterModel(new(Dict))
}

func (this *Dict) TableName() string {
	return models.TableName("dict")
}

type Day struct {
	Day   string `orm:"pk;column(day);"`
	Code  string
	Dayed int64
}

func init() {
	orm.RegisterModel(new(Day))
}

func (this *Day) TableName() string {
	return models.TableName("pms_day")
}

// 排序
type DictBySort []Dict

func (a DictBySort) Len() int           { return len(a) }
func (a DictBySort) Less(i, j int) bool { return a[i].Sort < a[j].Sort }
func (a DictBySort) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func GetAll() (dicts []Dict, err error) {
	o := orm.NewOrm()
	if _, err = o.QueryTable("dict").OrderBy("DictTypeCode", "Sort").All(&dicts); err != nil {
		// TODO 报错了没想好怎么补偿
	}
	return
}

func GetDict(id int64) (dict Dict, err error) {
	o := orm.NewOrm()
	dict = Dict{Id: id}
	if err = o.Read(&dict); err == orm.ErrNoRows {
		err = nil
	}
	return
}

func GetDictByDictId(dictId string) (dict Dict, err error) {
	o := orm.NewOrm()
	if err = o.QueryTable(models.TableName("dict")).Filter("dict_id", dictId).One(&dict); err == orm.ErrNoRows {
		err = nil
	}
	return
}

/**
字典的fileter过滤
*/
func DictFilter(stu []Dict, f func(s Dict) bool) []Dict {
	var r []Dict

	for _, s := range stu {
		if f(s) == true {
			r = append(r, s)
		}
	}

	return r
}

/**
根据分类和字典获取
*/
func GetDictByTypeAndDictId_(dictType, dictId string, projectid int64) Dict {
	if utils.IsEmpty(dictType) || utils.IsEmpty(dictId) {
		return Dict{}
	}
	condArr := make(map[string]interface{})
	//condArr["dictType"] = dictType
	//condArr["dictid"] = dictId
	dto := DictListExec(condArr)
	// 如果项目id为空，使用项目id查询，
	result := DictFilter(dto, func(s Dict) bool {
		if !utils.IsEmpty(projectid) && s.ProjectId == projectid && s.DictId == dictId && s.DictTypeCode == dictType {
			return true
		} else {
			return false
		}
		return true
	})
	// 如果项目查询为空使用公共id查询
	if utils.IsEmpty(result) {
		result = DictFilter(dto, func(s Dict) bool {
			if s.ProjectId == 0 && s.DictId == dictId && s.DictTypeCode == dictType {
				return true
			} else {
				return false
			}
			return true
		})
	}
	if !utils.IsEmpty(result) {
		return result[0]
	} else {
		return Dict{}
	}
}

/**
  添加字典
*/
func AddDict(updPro Dict) error {
	o := orm.NewOrm()
	pro := new(Dict)
	pro.Id = updPro.Id
	copier.Copy(pro, updPro)
	_, err := o.Insert(pro)
	return err
}

/**
修改字典
*/
func UpdateDict(id int64, updPro Dict) error {
	o := orm.NewOrm()
	pro := new(Dict)
	utils.SimpleCopyProperties(pro, updPro)
	_, err := o.Update(&pro)
	return err
}

/**
  分页查询字典
*/
func DictPageExec(condArr map[string]interface{}, page int, offset int) (ops []Dict) {
	o := orm.NewOrm()
	var dto []Dict
	o.Raw(dictPageSql(condArr, 1, page, offset)).QueryRows(&dto)
	return dto
}

/**
  分页查询字典
*/
func DictListExec(condArr map[string]interface{}) (ops []Dict) {
	o := orm.NewOrm()
	var dto []Dict
	err := utils.GetCache("Getdict", &dto)
	if err != nil {
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		o.Raw(dictPageSql(condArr, 1, 0, 2000)).QueryRows(&dto)
		utils.SetCache("Getdict", dto, cache_expire)
	}
	return dto
}

/**

 */
func DictPageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var ProjectsModuleDto int64
	o.Raw(dictPageSql(condArr, 1, page, offset)).QueryRow(&ProjectsModuleDto)
	return ProjectsModuleDto
}

/**
  组装sql
*/
func dictPageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT * FROM  pms_dict pp WHERE status = 0 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["dictType"]) {
		sql = sql + ` and  pp.dict_type_code in(`
		sql1, value := cores.SqlInParam(condArr["dictType"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	if !utils.IsEmpty(condArr["projectid"]) {
		sql = sql + ` and  pp.project_id in(`
		sql1, value := cores.SqlInParam(condArr["projectid"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	if !utils.IsEmpty(condArr["dictid"]) {
		sql = sql + ` and  pp.dict_id in(`
		sql1, value := cores.SqlInParam(condArr["dictid"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by dict_type_code,sort  LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}

/**
  查询日历
*/
func DayListExec(condArr map[string]interface{}) (ops []Day) {
	o := orm.NewOrm()
	var dto []Day
	err := utils.GetCache("Getday", &dto)
	if err != nil {
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		sql := `SELECT * FROM  pms_day pp WHERE 1=1 `
		o.Raw(sql).QueryRows(&dto)
		utils.SetCache("Getday", dto, cache_expire)
	}
	return dto
}
